package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallArticles;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.service.LitemallStorageService;
import org.linlinjava.litemall.db.service.PiccArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/wx/articles")
@Validated
public class WxPiccArticlesController {
    private final Log logger = LogFactory.getLog(WxPiccArticlesController.class);

    @Autowired
    PiccArticlesService articlesService;

    @Autowired
    LitemallStorageService storageService;

    /**
     * wx 客户端获取所有文章记录的路由
     * @param page
     * @param limit
     * @param deleted
     * @param sort
     * @return 返回联合查询的结果，联合了文章表和storage表，携带headerUrl type
     */
    @GetMapping("/list")
    public Object list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @RequestParam(defaultValue = "0") Integer deleted,
                       @RequestParam(defaultValue = "update_time") String sort) {
        return articlesService.getAllArticles(deleted, page, limit, sort);
    }

    //create视频
    @PostMapping("/create")
    public Object create(@RequestBody LitemallArticles article) {
        if (article.getHeaderId() == 0){
            //护士小程序，将视频上传到阿里云之后，无法获取id
            LitemallStorage storage = new LitemallStorage();
            //storage.setUrl(article.getDetailUrl());
            storage.setType("video/mp4");
            storage.setKey("empty");
            storage.setName("empty");
            storage.setSize(100);
            String videoUrl = article.getDetailUrl();
            //创建header的预览，视频服务就截帧
            videoUrl += "?x-oss-process=video/snapshot,t_5000,f_jpg,m_fast";
            storage.setUrl(videoUrl);
            storageService.add(storage);
            logger.debug("LJF---> make the header of video: "+storage);
            article.setHeaderId(storage.getId());
        }

        article.setAddTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        logger.debug("wx create articles: "+article);
        articlesService.create(article);
        return ResponseUtil.ok(article);
    }
}
